//
//  workday.swift
//  HanMeiMei
//
//  Created by xiaoyu on 2019/1/24.
//

import Foundation

var globalWorkDayDictionary : Dictionary<String, Int> = Dictionary.init()
var retrytime = 0

public func workday(day:String, complete: ((Bool)->(Void))?) -> Void {
    let storedType = globalWorkDayDictionary[day]
    if (storedType != nil) {
        if (storedType == 100 + 0) {
            complete?(true)
            return
        }else if (storedType == 100 + 1) {
            complete?(false)
            return
        }else if (storedType == 100 + 2) {
            complete?(false)
            return
        }else if (storedType == 500 + 100) {
            if (retrytime < 5) {
                retrytime += 1
            }else{
                complete?(false)
                return
            }
        }
    }
    
    let s_t = Int32(Date.init().timeIntervalSince1970)
    print("Start Workday Request... at \(s_t)")
    
    let url = "http://api.goseek.cn/Tools/holiday?date=" + day
    let req = URLRequest.init(url: (URL.init(string: url) ?? nil)!)
    
    let session = URLSession.init(configuration: .default)
    let semaphore = DispatchSemaphore(value: 0)
    
    let sessionTask = session.dataTask(with: req, completionHandler: { (data, resp, error) in
        semaphore.signal()
        guard let httpResp = resp as? HTTPURLResponse else {
            print("request error: \(error!)")
            globalWorkDayDictionary[day] = 500 + 100
            session.finishTasksAndInvalidate()
            complete?(false)
            return
        }
        if (error != nil || httpResp.statusCode != 200) {
            print("request error: \(error!)")
            session.finishTasksAndInvalidate()
            globalWorkDayDictionary[day] = 500 + 100
            complete?(false)
            return
        } else {
            do {
                let dic = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! Dictionary<String, Any>
                //{code: 10000,data: 2}
                let code = dic["code"] as! Int
                let type = dic["data"] as! Int
                if code == 10000 {
                    retrytime = 0
                    // type 0 : 工作日 1 ：假日 2 ：节日
                    globalWorkDayDictionary.removeAll()
                    globalWorkDayDictionary[day] = type + 100
                    if (type == 0) {
                        print("\([day]) is Workday")
                        complete?(true)
                    }else if (type == 1) {
                        print("\([day]) is Weekend day")
                        complete?(false)
                    }else if (type == 2) {
                        print("\([day]) is holiday")
                        complete?(false)
                    }
                }else {
                    globalWorkDayDictionary[day] = 500 + 100
                    complete?(false)
                }
            } catch let error as NSError {
                globalWorkDayDictionary[day] = 500 + 100
                print("json error: \(error)")
                complete?(false)
            }
        }
        session.finishTasksAndInvalidate()
    })
    sessionTask.resume()
    semaphore.wait()
}
